#define  EE_H
#include "I2C.h"
#include "EEprom.h"
#include "r_cg_iwdt.h"

static void sub_X24C0X_Read( void );
static void sub_EEprom_CheckSum( void );
static unsigned char sub_X24C0X_ReadByte( unsigned int wAdd );

static unsigned char u8_EEWRCount;

void Init_EEprom( void )
{
  I2C_Init();
}

unsigned char sub_X24C0X_ReadByte( unsigned int u16_Add )
{
  unsigned char i;
  unsigned char u8_Order1,u8_Order2;
  
  if( u16_Add > 0xFF )
  {
    u8_Order1 = 0xa2;
    u8_Order2 = 0xa3;
  }
  else
  {
    u8_Order1 = 0xa0;
    u8_Order2 = 0xa1;
  }
  
  I2C_Start();
  I2C_WriteX( u8_Order1 );
  I2C_ACK();
  I2C_WriteX( ((unsigned char)u16_Add) );
  I2C_ACK();
  I2C_Start();
  I2C_WriteX( u8_Order2 );
  I2C_ACK();
  i = I2C_ReadX();
  I2C_Stop();
  I2C_Flash();
  return( i );
}

unsigned char EepromWriteControl( unsigned int u16_Add, unsigned char u8_Data )
{
  unsigned char i;
  unsigned char u8_Order1;
  
  if( u16_Add > 0xFF )
  {
    u8_Order1 = 0xa2;
 //   u8_Order2 = 0xa3;
  }
  else
  {
    u8_Order1 = 0xa0;
//    u8_Order2 = 0xa1;
  }
  
  i = 0;
    
  if( u8_EEWRCount < 5 )
  {
    I2C_Start();
    I2C_WriteX( u8_Order1 );
    I2C_ACK();
    I2C_WriteX( ((unsigned char)u16_Add) );
    I2C_ACK();
    I2C_WriteX( u8_Data );
    i = I2C_ACK();
    I2C_Stop();
    I2C_Delay( 0x10 );
    
    if( 0 == i )
    {
      u8_EEWRCount = 0;
    }
    else
    {
      u8_EEWRCount ++;
    }
  }
  
  return i;
}

void sub_X24C0X_Read( void )
{
  unsigned int i;

  for( i=0; i<(256); i++ )
  {
    R_IWDT_Restart();
    u8_EepromData[i] = sub_X24C0X_ReadByte( i );
  }

}

void EepromReadControl( void )
{
  sub_X24C0X_Read();
  sub_EEprom_CheckSum();
  
  if( u8_EepromErrorF )
  {
    sub_X24C0X_Read();
    sub_EEprom_CheckSum();
  }
  
  if( u8_EepromErrorF )
  {
    sub_X24C0X_Read();
    sub_EEprom_CheckSum();
  }
}

void sub_EEprom_CheckSum( void )
{
  unsigned int u16_Tmp,u16_Sum;
  unsigned int i;
  
  u16_Sum = 0;
  for( i=0; i<(254); i++ )
  {
    u16_Sum = u16_Sum + u8_EepromData[i];
  }
    
  u16_Tmp = u8_EepromData[254];
  u16_Tmp = u16_Tmp << 8;
  u16_Tmp = u16_Tmp + u8_EepromData[255];
  if( (u16_Tmp==u16_Sum)&&(0xAA==u8_EepromData[0]) )
  {
    u8_EepromErrorF = 0;
  }
  else
  {
    u8_EepromErrorF = 1;
    		//data error, reset data
    u8_EepromData[0x01] = 0;
    u8_EepromData[0x02] = 0;
    u8_EepromData[0x03] = 0;
  }

}




